<template>
  <div v-loading="loading">
      <div class="content-top">
          <span class="h1">项目管理</span>
          <span class="h2">行政区域</span>
      </div>
      <div class="content clearfix">
        <div class="tree">
            <div class="select">
                <label for="">工程项目:</label>
                <el-select v-model="project" placeholder="请选择" filterable @change="changePro()">
                    <el-option
                    v-for="item in options"
                    :key="item.ID"
                    :label="item.Name"
                    :value="item.ID">
                    </el-option>
                </el-select>
            </div>
            <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
            <div style="margin-top:10px;"></div>
            <el-tree :data="data" node-key="id" accordion  :expand-on-click-node="false" :filter-node-method="filterNode" :props="defaultProps" ref="tree2" @node-click="fnRegion" :highlight-current="true">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>
                  <el-button type="text" size="mini" @click="() => append(node,data)">
                    添加
                  </el-button>
                  <el-button type="text" size="mini" @click="() => edit(node,data)">
                    修改
                  </el-button>
                  <el-button type="text" size="mini" @click="() => remove(node, data)">
                    删除
                  </el-button>
                </span>
                <span style="width: 150px;float: left;overflow: hidden;">{{ node.label }}</span>
                
              </span>
            </el-tree>
        </div>
        <div class="contract">
          <div style="width:100%;text-align: center;">
            <span class="h1">合同模板</span>
            <el-tooltip class="item" effect="dark" content="将合同文本格式编辑在下框" placement="top">
              <span class="prompt">?</span>
            </el-tooltip>
          </div>
            <div class="con" id="editor">
              <div id="editor1"></div>
              <div id="editor2">
                
              </div>
            </div>
            <div class="footer clearfix">
                <div class="fl">
                    <span class="addres">行政区域路径：{{address}}</span>
                </div>
                <el-button class="fr" type="danger" @click="delTemp">删除</el-button>
                <el-button class="fr" @click="addTemp" style="margin-right:10px;">保存</el-button>
            </div>
        </div>
      </div>

      <div class="add">
        <el-dialog
        title="区域管理"
        :visible.sync="userTip"
        width="400px">
        <div class="adduserinfo">
            <el-form ref="form"  label-width="80px">
                <el-form-item label="区域名称">
                    <el-input v-model="quname"  placeholder="请输入区域名称"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="userTip = false">取 消</el-button>
            <el-button type="primary" @click="subAdd()">确 定</el-button>
        </span>
        </el-dialog>
    </div>

  </div>
</template>
<script>
import api from "../../axios/api";
let id = 1000;
export default {
  name: "projectRegion",
  data() {
    return {
      loading: false,
      input: "",
      filterText: "",
      userTip: false,
      quname: "",
      datas: "",
      data: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      options: [], //工程项目列表
      project: "", //工程项目选中
      Region: [],
      ID: "", //当前点击区域的ID
      temID: "", //合同ID
      address: "", //行政区域路径
      state: "add" //判断时添加还是修改
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  },
  mounted() {
    var E = window.wangEditor;
    var editor = new E("#editor1", "#editor2"); // 两个参数也可以传入 elem 对象，class 选择器
    editor.create();
    this.getProject();
  },
  methods: {
    //获取工程项目列表
    getProject() {
      let me = this;
      this.$post(api.getlistde).then(response => {
        if (response.isOK == true && response.state == 200) {
          this.options = response.Data;
          this.project = response.Data[0].ID;
          this.getRegion();
        }else{
          this.$message.error(response.msg);
        }
      }).catch((error)=>{
        this.loading=false;
      })
    },
    //获取行政区域
    getRegion() {
      let me = this;
      this.loading = true;
      this.$get(api.anonymousget + "/" + this.project)
        .then(response => {
          if (response.data.isOK == true && response.data.state == 200) {
            this.loading = false;
            if (response.data.Data) {
              for (var i = 0; i < response.data.Data.length; i++) {
                response.data.Data[i].label = response.data.Data[i].RegionName;
              }
              me.data = this.HandleData(response.data.Data);
              me.ID = me.data[0].ID;
              me.address = me.data[0].RegionName;
              this.getTemp(me.ID);
            } else {
              this.$message.error("没有区域数据");
            }
          } else {
            this.loading = false;
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          this.loading = false;
        });
    },
    //修改行政区域的数据结构
    HandleData(data) {
      function toTree(data) {
        // 删除 所有 children,以防止多次调用
        data.forEach(function(item) {
          delete item.children;
        });
        // 将数据存储为 以 id 为 KEY 的 map 索引数据列
        var map = {};
        data.forEach(function(item) {
          map[item.ID] = item;
        });
        //        console.log(map);
        var val = [];
        data.forEach(function(item) {
          // 以当前遍历项，的pid,去map对象中找到索引的id
          var parent = map[item.ParentID];
          // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
          if (parent) {
            (parent.children || (parent.children = [])).push(item);
          } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
          }
        });
        return val;
      }
      return toTree(data);
    },
    //改变项目时重新拉取区域
    changePro() {
      this.getRegion();
    },

    //添加区域弹窗
    append(node, data) {
      this.state = "add";
      this.quname = "";
      this.userTip = true;
      this.Region = data;
    },
    //修改区域
    edit(node, data) {
      this.state = "edit";
      this.quname = data.RegionName;
      this.userTip = true;
      this.Region = data;
    },
    //确认添加修改区域
    subAdd() {
      let me = this;
      if (this.quname == "") {
        this.$message.error("请输入区域名称");
        return false;
      }
      this.loading = true;
      this.userTip = false;
      if (this.state == "add") {
        this.$post(api.addreg, {
          ParentID: this.Region.ID,
          ProjectID: this.Region.ProjectID,
          RegionName: this.quname
        })
          .then(response => {
            if (response.isOK == true && response.state == 200) {
              this.loading = false;
              this.getRegion();
              this.$message({
                type: "success",
                message: "添加成功!"
              });
            } else {
              this.loading = false;
              this.$message.error(response.msg);
            }
          })
          .catch(error => {
            this.loading = false;
          });
      } else if (this.state == "edit") {
        this.$post(api.editreg, {
          ID: this.Region.ID,
          RegionName: this.quname
        })
          .then(response => {
            if (response.isOK == true && response.state == 200) {
              this.loading = false;
              this.getRegion();
              this.$message({
                type: "success",
                message: "修改成功!"
              });
            } else {
              this.loading = false;
              this.$message.error(response.msg);
            }
          })
          .catch(error => {
            this.loading = false;
          });
      }
      this.quname = "";
    },
    //删除行政区域
    remove(node, data) {
      this.$confirm("将永久删除该区域, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.loading = true;
          this.$get(api.delreg + "/" + data.ID)
            .then(response => {
              if (response.data.isOK == true && response.data.state == 200) {
                this.loading = false;
                this.getRegion();
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
              } else {
                this.loading = false;
                this.$message.error(response.data.msg);
              }
            })
            .catch(error => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //获取当前点击的区域
    fnRegion(data) {
      this.ID = data.ID;
      //获取指定ID的全路径
      this.$get(api.anonychild + "/" + data.ID)
        .then(response => {
          if(response.data.isOK==true&& response.data.state == 200){
            this.address = response.data.Data.ResultString;
            this.getTemp(data.ID);
          }else{
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {});
      //获取指定ID的所以上级
      this.$get(api.getParent + "/" + data.ID)
        .then(response => {
          console.log(response);
          // this.address = response.data.msg;
          // this.getTemp(data.ID);
        })
        .catch(error => {
          this.loading=false;
        });
    },
    //获取合同模板
    getTemp(id) {
      this.loading = true;
      this.$get(api.getTemp + "/" + id)
        .then(response => {
          if (response.data.isOK == true && response.data.state == 200) {
            this.loading = false;
            if (response.data.Data.length != 0) {
              this.temID = response.data.Data[0].ID;
              $("#editor2 div").html(response.data.Data[0].TemplateContent);
            } else {
              $("#editor2 div").html(`<div>
                  <h4 style="text-align:center"><u>&nbsp;[     {0}    ]&nbsp;</u>工程征地拆迁补偿协议书</h4>
                  <p>
                    甲方：<span style="color:red">{1}</span>人民政府</p>
                    <p>
<p>乙方：  <u>&nbsp;&nbsp;{2}&nbsp;&nbsp;</u>  身份证号码  <u>&nbsp;&nbsp;{3}&nbsp;&nbsp;</u></p>
<p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;甲方根据《中华人民共和国土地管理法》和<u>&nbsp;&nbsp;[{0}]&nbsp;&nbsp;</u>工程建设的需要，需征收乙方土地，四至界址详见本项目相关工程四至界址土地测绘图所示。按照<u>&nbsp;&nbsp;<span style="color:red">[{1}]</span> &nbsp;&nbsp;</u>人民政府公布的本项目征地拆迁补偿标准规定，经双方协商一致，达成如下协议：</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;一、乙方同意甲方征收该项目建设用地范围内权属为乙方的土地及迁移地上附着青苗/竹木果树等/房屋/坟山，并由甲方补偿人民币￥<u>&nbsp;&nbsp;[{4}]&nbsp;&nbsp;</u>（大写：<u>&nbsp;&nbsp;[{5}]&nbsp;&nbsp;</u>），具体见乙方签字确认的附件（相关补偿登记/结算表 <u>&nbsp;&nbsp;[{6}]&nbsp;&nbsp;</u> 份）为准。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;二、甲方在本协议签订后5个工作日内向乙方一次性支付土地及地上附着青苗/竹木果树等/房屋/坟山补偿款。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;三、乙方必须在本协议签订后15天内自行完成征用地块内的青苗/竹木果树等/房屋/坟山迁移等事项（另有规定时间的，以其为准），并将相应地块交甲方施工使用，逾期不清理的，视为乙方自动放弃其权益，地上所有附着物的所有权自动归甲方，由甲方全权无偿处理。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;四、本协议一式肆份，甲方、乙方、业主、县级征地拆迁工程指挥部各存一份。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;五、本协议经双方签字后即生效，具有法律效力，双方必须共同遵守。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;六、本项目征地拆迁补偿依据的文件。</p>
 </br>
<p>甲方：<span style="color:red">{1}</span>人民政府（盖章）    负责人签字 <U>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</U></p>                 
 </br>
<p>乙方签字或乙方代表（摁手印）：<u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u>   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;       身份证号码： <u>&nbsp;&nbsp;[{3}]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> </p>
</br>
<p>村民委员会：   <u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u>（签名盖章）   负责人签字<u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u>      </p>           
</br>
<p>组织签订协议人员（自选）： <u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{7}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> </p>                               
                </div>`);
            }
          } else {
            this.loading = false;
            this.$message.error(response.msg);
          }
        })
        .catch(error => {
          this.loading = false;
        });
    },
    //新建合同模板
    addTemp() {
      this.loading = true;
      var content = $("#editor2 div").html();
      this.$post(api.addtemp, {
        ID: this.temID,
        RegionID: this.ID,
        TemplateContent: content
      })
        .then(response => {
          if (response.isOK == true && response.state == 200) {
            this.loading = false;
            this.$message({
              type: "success",
              message: "合同保存成功!"
            });
            this.getTemp(this.ID);
          } else {
            this.loading = false;
            this.$message.error(response.msg);
          }
        })
        .catch(error => {
          this.loading = false;
        });
    },
    //删除合同模板
    delTemp() {
      this.loading = true;
      this.$get(api.deltemp + "/" + this.temID)
        .then(response => {
          if (response.data.isOK == true && response.data.state == 200) {
            this.loading = false;
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getTemp(this.ID);
          } else {
            this.loading = false;
            this.$message.error(response.msg);
          }
        })
        .catch(error => {
          this.loading = false;
        });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    }
  }
};
</script>


<style scoped>
.content .select {
  width: 100%;
  margin-bottom: 10px;
}
.content .select label {
  display: inline-block;
  width: 80px;
  line-height: 40px;
}
.title {
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 10px;
}
.content {
  width: 1200px;
  margin: auto;
      z-index: 1;
  /* width: 100%; */
  /* display: flex;
  justify-content: center;
  align-items: center; */
}
.content .tree {
  margin-right: 20px;
  width: 440px;
  float: left;
  /* height: 500px; */
}
.content .contract {
  width: 740px;
  float:left;
}
.content .contract .h1 {
  font-size: 20px;
  font-weight: 600;
}
.content .contract .con {
  position: relative;
  width: 100%;
  height: 503px;
  border: 1px solid #000;
  margin: 10px 0;
  box-sizing: border-box;
  z-index: 1;
}
.content .contract .footer {
  width: 100%;
  height: 40px;
  line-height: 40px;
}
textarea {
  width: 100%;
  height: 100%;
}
#editor2 {
  height: 470px;
}
.addres{
  color: red;
  font-weight: 600;
}
.custom-tree-node{
	 flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>

